package com.shiwaixiangcun.customer.ui.activity

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.widget.Toast
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.chad.library.adapter.base.BaseQuickAdapter
import com.google.gson.reflect.TypeToken
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.shiwaixiangcun.customer.GlobalApi
import com.shiwaixiangcun.customer.GlobalConfig
import com.shiwaixiangcun.customer.R
import com.shiwaixiangcun.customer.adapter.AdapterPhone
import com.shiwaixiangcun.customer.base.BaseActivity
import com.shiwaixiangcun.customer.entity.PhoneBean
import com.shiwaixiangcun.customer.interfaces.RequestPermissionType
import com.shiwaixiangcun.customer.module.houserenting.CommonDataEntity
import com.shiwaixiangcun.customer.ui.dialog.DialogLoginOut
import com.shiwaixiangcun.customer.utils.AppSharePreferenceMgr
import com.shiwaixiangcun.customer.utils.JsonUtil
import kotlinx.android.synthetic.main.activity_telephone.*
import kotlinx.android.synthetic.main.top_bar_white.*
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList

/**
 * 救助电话Activity
 *
 * @author Administrator
 */
class TelephoneActivity : BaseActivity(), AMapLocationListener {


    private var mAdapterPhone: AdapterPhone? = null
    var mList: MutableList<PhoneBean>? = null
    private var strToken: String? = null

    private var longitude: Double = 0.toDouble()
    private var latitude: Double = 0.toDouble()

    private var phoneNumber: String = ""

    /**
     * 高德定位
     */
    private var mLocationClient: AMapLocationClient? = null
    private var mLocationOption: AMapLocationClientOption? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_telephone)
        initData()
        initViewAndEvent()
        initLocation()
    }

    /**
     * 初始化定位
     */
    private fun initLocation() {
        mLocationClient = AMapLocationClient(this.applicationContext)
        mLocationOption = AMapLocationClientOption()

        mLocationClient!!.setLocationListener(this)

        mLocationOption!!.locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
        mLocationOption!!.interval = 3000
        mLocationOption!!.isOnceLocation = true

        mLocationClient!!.setLocationOption(mLocationOption)
        mLocationClient!!.startLocation()


    }

    private fun initViewAndEvent() {
        tv_page_name!!.text = "救助电话"

        back_left.setOnClickListener { finish() }

        mAdapterPhone = AdapterPhone(mList)
        rv_number!!.layoutManager = LinearLayoutManager(this)
        rv_number!!.adapter = mAdapterPhone

        mAdapterPhone?.onItemClickListener = BaseQuickAdapter.OnItemClickListener { adapter, view, position ->
            val phoneBean = mAdapterPhone?.data?.get(position)
            phoneNumber = phoneBean?.number!!
            val dialogLoginOut = DialogLoginOut(mContext, R.layout.item_dialog_call_phone)
            dialogLoginOut.setTitle("是否要拨打此电话？")
            dialogLoginOut.setMessage(phoneBean.number)
            dialogLoginOut.setYesOnclickListener("是", {
                phoneBean.title?.let { putData(it) }
                dialogLoginOut.dismiss()
                requestPermission(phoneNumber)
            })

            dialogLoginOut.setNoOnclickListener("否") { dialogLoginOut.dismiss() }
            dialogLoginOut.show()
        }
    }


    private fun requestPermission(number: String?) {
        //判断Android版本是否大于23
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)

            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CALL_PHONE),
                        RequestPermissionType.REQUEST_CODE_ASK_CALL_PHONE)
                return
            } else {
                callPhone(number)
            }
        } else {
            callPhone(number)
        }
    }


    /**
     * 注册权限申请回调
     * @param requestCode 申请码
     * @param permissions 申请的权限
     * @param grantResults 结果
     */
    @Override
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        when (requestCode) {
            RequestPermissionType.REQUEST_CODE_ASK_CALL_PHONE -> if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                callPhone(phoneNumber)
            } else {
                // Permission Denied
                Toast.makeText(this, "CALL_PHONE Denied", Toast.LENGTH_SHORT).show()
            }
            else -> super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        }
    }

    /**
     * 拨号方法
     */
    @SuppressLint("MissingPermission")
    private fun callPhone(number: String?) {
        val intent = Intent(Intent.ACTION_CALL, Uri.parse("tel:" + number))
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        startActivity(intent)
    }

    /**
     * @param title
     */
    private fun putData(title: String) {
        strToken = AppSharePreferenceMgr.get(mContext, GlobalConfig.TOKEN, "") as String
        OkGo.post<String>(GlobalApi.callSOS)
                .params("access_token", strToken)
                .params("callObject", title)
                .params("longitude", longitude)
                .params("latitude", latitude)
                .execute(object : StringCallback() {
                    override fun onError(response: Response<String>) {
                        super.onError(response)
                        Log.e(BUG_TAG, response.toString())
                        Log.e(BUG_TAG, "error")
                    }

                    override fun onSuccess(response: Response<String>) {
                        val type = object : TypeToken<CommonDataEntity<Any>>() {

                        }.type
                        val responseEntity = JsonUtil.fromJson<CommonDataEntity<Any>>(response.body(), type)
                        if (responseEntity != null) {
                            when (responseEntity.responseCode) {
                                1001 -> Log.e(BUG_TAG, "success")
                                else -> Log.e(BUG_TAG, "fail")
                            }
                        }
                    }
                })

    }

    private fun initData() {
        mList = ArrayList()

        val first = PhoneBean("天鹅堡智慧康养服务中心", "400-999-8871")
        val hospital = PhoneBean("天鹅堡医院", "0851-28798777")

        val wuye = PhoneBean("天鹅堡物业中心", "0851-22851555")

        val jingwushi = PhoneBean("天鹅堡警务室", "0851-28790151")
        val jiudian = PhoneBean("酒店前台", "0851-23313111")

        val Aqu = PhoneBean("A区区域管家", "13027872786")
        val Bqu = PhoneBean("B区区域管家", "13087897558")

        val Equ = PhoneBean("E区1-16栋管家", "15599222838")
        val Equ32 = PhoneBean("E区17-32栋管家", "13096735118")
        val Equ49 = PhoneBean("E区33-49栋管家", "15599225286")

        mList?.add(first)
        mList?.add(hospital)
        mList?.add(wuye)
        mList?.add(jingwushi)
        mList?.add(jiudian)
        mList?.add(Aqu)
        mList?.add(Bqu)
        mList?.add(Equ)
        mList?.add(Equ32)
        mList?.add(Equ49)


    }


    override fun onDestroy() {
        super.onDestroy()
        destroyLocation()

    }

    private fun destroyLocation() {
        if (null != mLocationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            mLocationClient!!.onDestroy()
            mLocationClient = null
            mLocationOption = null
        }


    }

    /**
     * 位置改变
     *
     * @param aMapLocation
     */
    override fun onLocationChanged(aMapLocation: AMapLocation?) {
        if (aMapLocation != null) {
            if (aMapLocation.errorCode == 0) {
                //定位成功回调信息，设置相关消息
                aMapLocation.locationType//获取当前定位结果来源，如网络定位结果，详见定位类型表
                latitude = aMapLocation.latitude//获取纬度
                longitude = aMapLocation.longitude//获取经度
                aMapLocation.accuracy//获取精度信息
                val df = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                val date = Date(aMapLocation.time)
                df.format(date)//定位时间
            } else {
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + aMapLocation.errorCode + ", errInfo:"
                        + aMapLocation.errorInfo)
            }
        }

    }


}
